//
//  FYProductDetailPage.m
//  ThePainter
//
//  Created by Sean on 15/8/17.
//  Copyright (c) 2015年 FeiYu. All rights reserved.
//

#import "FYProductDetailPage.h"
#import "FYProductDetialViewModel.h"
#import "MJRefresh.h"
#import "FYProductDetial.h"
#import "FYComment.h"
#import "FYCommentView.h"

@interface FYProductDetailPage ()

@property (nonatomic) FYProductDetialViewModel *viewModel;
@property (nonatomic) NSString *productId;
@property (nonatomic) UIScrollView *scrollView;
@property (nonatomic) UIView *container;
@property (nonatomic) FYProductDetial *productDetial;
@property (nonatomic) CGFloat sW;
@property (nonatomic) CGFloat sH;
@property (nonatomic) UIView *descCon;
@property (nonatomic) UIView *commentCon;
@property (nonatomic) NSArray *comments;

- (void)initView;

- (void)initRefreshHeader;

- (void)initRefreshFoot;

- (void)layoutView;

- (void)refreshView;

@end

@implementation FYProductDetailPage

- (id)initWithProductId:(NSString*)productId {
    if (self = [super init]) {
        self.productId = productId;
        self.viewModel = [[FYProductDetialViewModel alloc] init];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //设置nav标题
    self.title = @"详情";
    
    [self initView];
//    [self initRefreshHeader];
    [self initRefreshFoot];
    [self loadNewData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initView {
    
    self.sW = [FYUtils fyScreenWidth];
    self.sH = [FYUtils fyScreenHeight];
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.backgroundColor = [UIColor whiteColor];
    //这里必须这样设置不然显示不出来(原因未知)
    self.scrollView.contentSize = CGSizeMake(self.sW, self.sH);
    [self.view addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    //scroll view 容器
    self.container = [[UIView alloc] init];
    [self.scrollView addSubview:self.container];
    [self.container mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.scrollView);
        make.width.equalTo(self.scrollView);
    }];
}

- (void)initRefreshHeader {
    
    NSArray *idleImages = @[[UIImage imageNamed:@"loading_1"]];
    NSArray *pullingImages = @[[UIImage imageNamed:@"loading_1"],
                               [UIImage imageNamed:@"loading_2"],
                               [UIImage imageNamed:@"loading_3"],
                               [UIImage imageNamed:@"loading_4"]];
    NSArray *refreshingImages = pullingImages;
    
    //下拉刷新
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    // 设置普通状态的动画图片
    [header setImages:idleImages forState:MJRefreshStateIdle];
    // 设置即将刷新状态的动画图片（一松开就会刷新的状态）
    [header setImages:pullingImages forState:MJRefreshStatePulling];
    // 设置正在刷新状态的动画图片
    [header setImages:refreshingImages forState:MJRefreshStateRefreshing];
    // 隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES;
    // 隐藏状态
    header.stateLabel.hidden = YES;
    // 设置header
    self.scrollView.header = header;
}

- (void)initRefreshFoot {
    
    NSArray *refreshingImages = @[[UIImage imageNamed:@"loading_1"],
                                  [UIImage imageNamed:@"loading_2"],
                                  [UIImage imageNamed:@"loading_3"],
                                  [UIImage imageNamed:@"loading_4"]];
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadMoreData方法）
    MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    // 设置刷新图片
    [footer setImages:refreshingImages forState:MJRefreshStateRefreshing];
    // 设置尾部
    self.scrollView.footer = footer;
}

- (void)loadNewData {
    [self.viewModel loadNewData:self.productId valueBlock:^(id returnValue) {
        self.productDetial = returnValue;
        self.comments = self.productDetial.comments;
        [self layoutView];
        [self finishLoadNewData];
    } errorBlock:^(id errorCode) {
        [self finishLoadNewData];
    } failureBlock:^{
        [self finishLoadNewData];
    }];
}

- (void)loadMoreData {
    [self.viewModel loadMoreData:self.productId valueBlock:^(id returnValue) {
        self.comments = returnValue;
        [self refreshView];
        [self finishLoadMoreData];
    } errorBlock:^(id errorCode) {
        
    } failureBlock:^{
        [self noMoreData];
    }];
}

- (void)finishLoadNewData {
    [self.scrollView.header endRefreshing];
}

- (void)finishLoadMoreData {
    [self.scrollView.footer endRefreshing];
}

- (void)noMoreData {
    [self.scrollView.footer noticeNoMoreData];
}

- (void)resetNoMore {
    [self.scrollView.footer resetNoMoreData];
}

- (void)layoutView {
    
    CGFloat picW = self.sW;
    CGFloat picH = picW;
    //图片间隔
    CGFloat dis = 7;
    UIImageView *lastView = nil;
    
    for (NSString *productPic in self.productDetial.productPics) {
        
        UIImageView *pic = [[UIImageView alloc] init];
        pic.backgroundColor = [UIColor clearColor];
        [self.container addSubview:pic];
        
        //自动布局
        [pic mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.and.right.equalTo(self.container);
            make.height.mas_equalTo(@(picH));
            if (lastView) {
                make.top.mas_equalTo(lastView.mas_bottom).with.offset(dis);
            } else {
                make.top.mas_equalTo(self.container.mas_top);
            }
        }];
        
        //下载图片
        SDWebImageManager *manager = [SDWebImageManager sharedManager];
        [manager downloadImageWithURL:[NSURL URLWithString:productPic] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            
        } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
            if (image) {
                CGFloat imgW = image.size.width;
                CGFloat imgH = image.size.height;
                CGFloat scale = imgH / imgW;
                [pic mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.height.mas_equalTo(@(picW * scale));
                }];
                pic.image = image;
            }
        }];
        
        lastView = pic;
    }
    
    //简介
    self.descCon = [[UIView alloc] init];
    self.descCon.backgroundColor = [UIColor clearColor];
    [self.container addSubview:self.descCon];
    [self.descCon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.container);
        make.top.equalTo(lastView.mas_bottom).with.offset(dis);
    }];
    
    //介绍
    CGFloat dW = self.descCon.frame.size.width - 10;
    FYDesc *labDesc = [[FYDesc alloc] initWithString:self.productDetial.desc fontSize:fyLabSize3 color:[UIColor blackColor] width:dW];
    [self.descCon addSubview:labDesc];
    [labDesc mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.descCon).offset(5);
        make.right.equalTo(self.descCon).offset(-5);
        make.top.equalTo(self.descCon.mas_top).with.offset(dis);
    }];
    
    //横线
    UIView *line1 = [[UIView alloc] init];
    line1.backgroundColor = fyColorLightGary;
    [self.descCon addSubview:line1];
    [line1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(@(0.5));
        make.left.equalTo(self.descCon).with.offset(dis);
        make.right.equalTo(self.descCon).with.offset(- dis);
        make.top.equalTo(labDesc.mas_bottom).with.offset(dis);
    }];

    //头像
    CGFloat aW = 50;
    UIImageView *imgAvatar = [[UIImageView alloc] init];
    imgAvatar.backgroundColor = [UIColor clearColor];
    imgAvatar.layer.cornerRadius = aW / 2;
    imgAvatar.layer.masksToBounds = YES;
    [imgAvatar sd_setImageWithURL:[NSURL URLWithString:self.productDetial.user.avatar] placeholderImage:[UIImage imageNamed:@"icon_set_avatar"]];
    [self.descCon addSubview:imgAvatar];
    [imgAvatar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(@(aW));
        make.width.mas_equalTo(@(aW));
        make.top.equalTo(line1.mas_bottom).offset(dis);
        make.left.equalTo(self.descCon).offset(dis);
        make.bottom.equalTo(self.descCon.mas_bottom).offset(-dis);
    }];
    
    //名字
    FYLabel *labName = [[FYLabel alloc] initWithString:self.productDetial.user.username size:fyLabSize3 color:[UIColor blackColor]];
    [self.descCon addSubview:labName];
    [labName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(imgAvatar.mas_top).offset(dis);
        make.left.equalTo(imgAvatar.mas_right).offset(dis);
    }];
    
    //评论容器
    self.commentCon = [[UIView alloc] init];
    self.commentCon.backgroundColor = [UIColor whiteColor];
    [self.container addSubview:self.commentCon];
    [self.commentCon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.container);
        make.top.equalTo(self.descCon.mas_bottom).with.offset(dis);
    }];
    
    //显示评论内容
    [self refreshView];
    
    [self.container mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.commentCon.mas_bottom);
    }];
}

- (void)refreshView {
    for (UIView *view in self.commentCon.subviews) {
        [view removeFromSuperview];
    }
    
    CGFloat dis = 7;
    
    //分割线
    UIView *lineBlod = [[UIView alloc] init];
    lineBlod.backgroundColor = fyColorLightGary;
    [self.commentCon addSubview:lineBlod];
    [lineBlod mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@(4));
        make.top.equalTo(self.commentCon.mas_top);
        make.left.equalTo(self.commentCon.mas_left);
        make.right.equalTo(self.commentCon.mas_right);
    }];
    
    //评论标题
    NSString *newCom = [NSString stringWithFormat:@"最新评论 (评论共%lu条)", (unsigned long)self.comments.count];
    FYLabel *labNewCom = [[FYLabel alloc] initWithString:newCom size:fyLabSize3 color:[UIColor blackColor]];
    [self.commentCon addSubview:labNewCom];
    [labNewCom mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.commentCon.mas_left).offset(dis);
        make.top.equalTo(lineBlod.mas_bottom).offset(dis);
    }];
    
    //横线
    UIView *line2 = [[UIView alloc] init];
    line2.backgroundColor = fyColorLightGary;
    [self.commentCon addSubview:line2];
    [line2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(@(0.5));
        make.left.equalTo(self.commentCon.mas_left);
        make.right.equalTo(self.commentCon.mas_right);
        make.top.equalTo(labNewCom.mas_bottom).with.offset(dis);
    }];
    
    if (self.comments.count > 0) {
        //评论框
        FYCommentView *lastCV = nil;
        for (FYComment *comment in self.comments) {
            FYCommentView *cv = [[FYCommentView alloc] initWithComment:comment];
            [self.commentCon addSubview:cv];
            [cv mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.and.right.equalTo(self.commentCon);
                if (lastCV) {
                    make.top.equalTo(lastCV.mas_bottom);
                } else {
                    make.top.equalTo(line2.mas_bottom);
                }
            }];
            lastCV = cv;
        }
        //commentCon底部和最后一个评论框对齐
        [self.commentCon mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(lastCV.mas_bottom);
        }];
    } else {
        FYLabel *labNoComment = [[FYLabel alloc] initWithString:@"暂无评论~" size:fyLabSize3 color:[UIColor blackColor]];
        [self.commentCon addSubview:labNoComment];
        [labNoComment mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(line2.mas_bottom).offset(dis);
            make.centerX.equalTo(self.commentCon.mas_centerX);
        }];
        //commentCon底部和提示标语对齐
        [self.commentCon mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(labNoComment.mas_bottom).offset(dis);
        }];
    }
}

@end
